package com.lanou3g.bookstore.user.web.servlet;

import com.lanou3g.bookstore.cart.domain.Cart;
import com.lanou3g.bookstore.user.domain.User;
import com.lanou3g.bookstore.user.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "UserServlet", urlPatterns = "/login.do")
public class UserServlet extends HttpServlet {
    private UserService userService = new UserService();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        if ("".equals(username) || username == null) {
            request.setAttribute("msg", "用户名不能为空");
            request.getRequestDispatcher("/jsps/user/login.jsp")
                    .forward(request, response);
            return;
        }
        String password = request.getParameter("password");
        if ("".equals(password) || password == null) {
            request.setAttribute("msg", "密码不能为空");
            request.getRequestDispatcher("/jsps/user/login.jsp")
                    .forward(request, response);
            return;
        }
        User form = new User();
        form.setUsername(username).setPwd(password);
        User user = userService.login(form);
        if (user == null) {
            request.setAttribute("msg", "用户名不存在/密码错误");
            request.getRequestDispatcher("/jsps/user/login.jsp")
                    .forward(request, response);
        } else {
            Cart cart = new Cart();
            request.getSession().setAttribute("user", user);
            request.getSession().setAttribute("cart", cart);
            response.sendRedirect(request.getContextPath() + "/jsps/msg.jsp");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getSession().invalidate();
        response.sendRedirect(request.getContextPath() + "/jsps/user/login.jsp");
    }
}
